<?php

namespace app\controllers;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class IndexController
{
	protected $request;

	public function __construct()
	{
		$this->request = Request::createFromGlobals();
	}

	public function index()
	{
		$input = $this->request->get('name', 'SFrame');

		$data = sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8'));

		return $data;
	}

	/**
	 * 代理请求 url
	 * @route /api/httpProxy
	 * @param string url: 代理请求的目标 url
	 * @param string method: 代理请求目标 url 时使用 get 还是 post，默认为 get
	 * @param string xxx: 其它任意一个或多个参数，将转发到目标 url
	 * @return mixed
	 * 正常时返回目标 url 的内容，
	 * 异常时返回：["code" => 0, "message" => "xxx", "data" => "", "headers" => "xxx", "response" => "xxx"]
	 */
	public function httpProxy()
	{
		$http = new \Http();
		$httpRequest = $http->request();
		$response = $http->response();

		$url = $http->getPost("url");
		$method = $http->getPost("method", "get");
		$params = $http->getPost();

		$url = urldecode($url);
		unset($params["url"], $params["method"]);

		$res = http_send($url, $params, $method);

		if (!in_array($res["code"], [200, 201, 202, 204, 205, 206])) {
			return $res;
		}

		return $res["data"];
	}
}
